<template>
  <div class="captcha-container">
    <div class="captcha-input-group">
      <el-input
        v-model="inputValue"
        :placeholder="placeholder"
        :prefix-icon="Key"
        clearable
        maxlength="4"
        class="captcha-input"
        @input="handleInput"
        @keyup.enter="$emit('enter')"
      />
      <div class="captcha-image" @click="refreshCaptcha">
        <img
          v-if="captchaImageUrl"
          :src="captchaImageUrl"
          :width="canvasWidth"
          :height="canvasHeight"
          class="captcha-img"
          alt="验证码"
        />
        <div v-else class="captcha-loading">
          加载中...
        </div>
        <div class="refresh-hint">点击刷新</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Key } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as captchaApi from '@/api/modules/captcha'

interface Props {
  modelValue?: string
  placeholder?: string
  width?: number
  height?: number
}

interface Emits {
  (e: 'update:modelValue', value: string): void
  (e: 'change', value: string, isValid: boolean): void
  (e: 'captchaIdChange', captchaId: string): void
  (e: 'enter'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入验证码',
  width: 120,
  height: 40
})

const emit = defineEmits<Emits>()

// 响应式数据
const inputValue = ref(props.modelValue)
const captchaId = ref('')
const captchaImageUrl = ref('')
const currentCode = ref('')
const canvasWidth = ref(props.width)
const canvasHeight = ref(props.height)
const loading = ref(false)

// 生成验证码
const generateCaptcha = async () => {
  try {
    loading.value = true
    const response = await captchaApi.generateCaptcha()

    captchaId.value = response.data.captchaId
    captchaImageUrl.value = captchaApi.getCaptchaImageUrl(response.data.captchaId)

    // 开发环境可能返回验证码用于调试
    if (response.data.code) {
      // {{ AURA-X: Modify - 修复API响应数据结构访问错误，确保正确获取验证码. Approval: 寸止(ID:bug-fix-002). }}
      currentCode.value = String(response.data.code)
      console.log('验证码（仅开发环境）:', response.data.code)
    } else {
      // 如果没有返回验证码，重置为空字符串
      currentCode.value = ''
    }

    // 通知父组件验证码ID变化
    emit('captchaIdChange', captchaId.value)

  } catch (error: any) {
    console.error('生成验证码失败:', error)
    ElMessage.error('验证码加载失败，请刷新重试')
  } finally {
    loading.value = false
  }
}

// 刷新验证码
const refreshCaptcha = async () => {
  if (!captchaId.value) {
    // 如果没有验证码ID，生成新的
    await generateCaptcha()
    return
  }

  try {
    loading.value = true
    const response = await captchaApi.refreshCaptcha(captchaId.value)

    captchaImageUrl.value = captchaApi.getCaptchaImageUrl(response.data.captchaId)

    // 开发环境可能返回验证码
    if (response.data.code) {
      // {{ AURA-X: Modify - 修复API响应数据结构访问错误，确保正确获取验证码. Approval: 寸止(ID:bug-fix-002). }}
      currentCode.value = String(response.data.code)
      console.log('验证码（仅开发环境）:', response.data.code)
    } else {
      // 如果没有返回验证码，重置为空字符串
      currentCode.value = ''
    }

    // 清空输入框
    inputValue.value = ''
    emit('update:modelValue', '')
    emit('change', '', false)

  } catch (error: any) {
    console.error('刷新验证码失败:', error)
    ElMessage.error('验证码刷新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 验证验证码（本地验证，实际验证在后端）
const validateLocal = (): boolean => {
  if (!inputValue.value || inputValue.value.length !== 4) {
    return false
  }
  // 如果有开发环境的验证码，进行本地验证
  if (currentCode.value) {
    // {{ AURA-X: Modify - 添加类型安全检查，确保字符串类型后再调用toUpperCase. Approval: 寸止(ID:bug-fix-001). }}
    const currentCodeStr = String(currentCode.value)
    const inputValueStr = String(inputValue.value)
    return inputValueStr.toUpperCase() === currentCodeStr.toUpperCase()
  }
  // 否则返回true，让后端验证
  return true
}

// 处理输入
const handleInput = (value: string) => {
  const upperValue = value.toUpperCase()
  inputValue.value = upperValue
  emit('update:modelValue', upperValue)

  // 本地验证
  const isValid = validateLocal()
  emit('change', upperValue, isValid)
}

// 验证验证码是否正确（供父组件调用）
const validate = (): boolean => {
  return validateLocal()
}

// 获取验证码ID
const getCaptchaId = (): string => {
  return captchaId.value
}

// 获取当前验证码（用于调试）
const getCurrentCode = (): string => {
  return currentCode.value
}

// 监听props变化
watch(() => props.modelValue, (newValue) => {
  if (newValue !== inputValue.value) {
    inputValue.value = newValue
  }
})

// 暴露方法给父组件
defineExpose({
  validate,
  refresh: refreshCaptcha,
  getCaptchaId,
  getCurrentCode
})

// 组件挂载时初始化
onMounted(() => {
  generateCaptcha()
})
</script>

<style lang="scss" scoped>
.captcha-container {
  width: 100%;
}

.captcha-input-group {
  display: flex;
  gap: 12px;
  align-items: center;
}

.captcha-input {
  flex: 1;
  
  :deep(.el-input__wrapper) {
    background-color: var(--bg-color-tertiary);
    border: 1px solid var(--border-color-light);
    border-radius: 6px;
    padding: 8px 12px;
    transition: all 0.3s ease;
    box-shadow: none;
    min-height: 36px;

    &:hover {
      border-color: var(--theme-primary);
    }

    &.is-focus {
      border-color: var(--theme-primary);
      box-shadow: 0 0 0 2px var(--theme-primary-bg);
    }
  }

  :deep(.el-input__inner) {
    height: auto;
    line-height: 1.4;
    color: var(--text-color-primary);
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 2px;
    text-align: center;
    font-weight: 600;

    &::placeholder {
      color: var(--text-color-tertiary);
      text-transform: none;
      letter-spacing: normal;
      font-weight: normal;
    }
  }
}

.captcha-image {
  position: relative;
  cursor: pointer;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid var(--border-color-light);
  transition: all 0.3s ease;
  
  &:hover {
    border-color: var(--theme-primary);
    transform: scale(1.02);
    
    .refresh-hint {
      opacity: 1;
    }
  }
}

.captcha-img {
  display: block;
  background: white;
  border-radius: 4px;
}

.captcha-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 40px;
  background: #f5f5f5;
  color: #999;
  font-size: 12px;
  border-radius: 4px;
}

.refresh-hint {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

// 响应式设计
@media (max-width: 768px) {
  .captcha-input-group {
    gap: 8px;
  }
  
  .captcha-image {
    flex-shrink: 0;
  }
}
</style>
